<template>
  <el-dialog
    v-if="visible"
    v-model="visible"
    :width="fileType(src, 'audio') ? '360px' : '1000px'"
    :title="title || 'PDF预览'"
  >
    <audio v-if="fileType(src, 'audio')" :src="src" controls />
    <video 
      v-if="fileType(src, 'video')" 
      :src="src" 
      controls 
      width="960" 
    />
    <div v-if="fileType(src, 'file')" v-loading="loading">
      <iframe
        ref="pdf"
        :src="parseFilePath(src)"
        height="1200px"
        width="100%"
        border="0"
        :title="title"
        @load="loading = false"
      />
    </div>
  </el-dialog>
</template>
<script>
  import crypto from 'crypto-js'
  export default {
    data() {
      return {
        loading: false,
        visible: false,
        src: '',
        title: '',
        numPages: null // pdf 总页数
      }
    },

    methods: {
      fileType(filePath, type) {
        let fileType = filePath.split('.').pop()
        if (['mp3', 'wav'].includes(fileType) && type == 'audio') {
          return true
        }
        if (['mp4', 'rvmb'].includes(fileType) && type == 'video') {
          return true
        }
        if (
          ['doc', 'docx', 'ppt', 'xlsx', 'pdf', 'pptx', 'ppt'].includes(fileType) &&
          type == 'file'
        ) {
          return true
        }
        return false
      },
      parseFilePath(src) {
        let url = crypto.enc.Utf8.parse(src)
        url =
          import.meta.env.VITE_GLOB_APP_PREVIEW +
          '/onlinePreview?url=' +
          encodeURIComponent(crypto.enc.Base64.stringify(url))
        return url
      },
      show(src = '', title = '') {
        this.title = title
        if (!src) return this.$message.warning('文件不存在')
        this.src = src
        this.visible = true
        this.loading = true
        // this.loading = true
        // const loadingTask = pdf.createLoadingTask(this.src)
        // loadingTask.promise
        //   .then(pdf => {
        //     this.numPages = pdf.numPages
        //   })
        //   .catch(err => {
        //     console.error('pdf 加载失败', err)
        //   })
        //   .finally(() => {
        //     this.loading = false
        //   })
      },
      close() {
        this.src = ''
        this.visible = false
        this.numPages = null
      }
    }
  }
</script>
